<?php
namespace common\util;

use yii;
use linslin\yii2\curl\Curl;
use common\models\BaseRegion;
use common\models\BaseSupplierGoods;

/**
 * 
 * @Description: 公用不常用函数 
 * @author: kai.gao
 * @date: 2014-11-20 下午10:56:29
 */
class F {
	/**
	 * 
	 * @Title: getClientIP
	 * @Description: 获取客户端ip 
	 * @return: NULL|Ambigous <string, unknown>
	 * @author: kai.gao
	 * @date: 2014-11-20 下午10:56:42
	 */
	public static function IP() {
		static $ip = NULL;
		if ($ip !== NULL)
			return $ip;
		if (isset($_SERVER['HTTP_X_REAL_IP'])) {
			$ip = $_SERVER['HTTP_X_REAL_IP'];
		} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			$pos = array_search('unknown', $arr);
			if (false !== $pos)
				unset($arr[$pos]);
			$ip = trim($arr[0]);
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		$ip = ( false !== ip2long($ip) ) ? $ip : '0.0.0.0';
		return $ip;
	}
	
	/**
	 * @Title: getRegion
	 * @Description: 根据ip获取对应的省 市 
	 * @param string $ip 用户的IP
	 * @return: Ambigous <NULL, multitype:Ambigous <\yii\db\ActiveRecord, multitype:, NULL> >|NULL
	 * @author: kai.gao
	 * @date: 2014-12-13下午3:10:07
	 */
	public static function getRegion($ip) {
		$curl = new Curl();
		$result = $curl->get(IP_API.'?ip='.$ip, [], false);
		if ($result['code'] == 0 && $result['data']['region'] && $result['data']['city']) {
			$province = BaseRegion::find()->where(['region_name' => str_replace('省', '', $result['data']['region'])])->asArray()->one();
			$city = BaseRegion::find()->where(['region_name' => str_replace('市', '', $result['data']['city'])])->asArray()->one();
			return $province && $city ? ['procince' => $province, 'city' => $city, 'info' => $result['data']] : false;
		}
		return false;
	}
        
        

        
}